import java.util.*;

/**
 * @author LKQ
 * @date 2022/6/28 9:22
 * @description 思路：HashMap存储单词，如果单词两个字母相同，最终的单词；如果单词两个字母不同，那么相对应的一组可以添加进去，应该尽可能的多添加组
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] words = {"dd","aa","bb","dd","aa","dd","bb","dd","aa","cc","bb","cc","dd","cc"};
        solution.longestPalindrome(words);
    }
    public int longestPalindrome(String[] words) {
        Map<String, Integer> map = new HashMap<>();
        for (String word: words) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }
        int ans = 0;
        boolean add = true;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            String word = entry.getKey();
            int cnt = entry.getValue();
            if (word.charAt(0) == word.charAt(1)) {
                // 单词相同，偶数个直接统计进去
                if (cnt % 2 == 0) {
                    ans += cnt;
                }else {
                    // 奇数个数，第一次可以全部使用，后面的只能使用奇数个数减一
                    ans += add ? cnt : cnt - 1;
                    add = false;
                }
            }else {
                // 获取对应相反的字符串的个数
                String reverse  = "" + word.charAt(1) + word.charAt(0);
                int value = map.getOrDefault(reverse, 0);
                if (value == 0) {
                    continue;
                }
                int min = Math.min(value, cnt);
                ans += min;
            }
        }
        return ans * 2;
    }
}
